package com.xxx.base.controller;//放在common工程,好让以后其他模块也能使用文件上传功能,拷贝即可不需写!

import com.xxx.base.utils.R;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/minio")
public class MinIoController {
    private static final String ACCESSKEY = "minioadmin";
    private static final String SECREKEY = "minioadmin";
    private static final String ADDRESS = "http://localhost:9000";
    private static final String BUCKETNAME = "testbucket";

    //上传文件
    @PostMapping//
    public R<String> upload(@RequestPart("file") MultipartFile file) {
        try {
            // 构建一个Minio客户端
            MinioClient minioClient = MinioClient.builder()
                //创建容器时指定的账号
                .credentials(MinIoController.ACCESSKEY, MinIoController.SECREKEY)
                //上传地址
                .endpoint(MinIoController.ADDRESS).build();

            //处理文件名
            String oName = file.getOriginalFilename();
            
            String fileName = System.currentTimeMillis()+oName.substring(oName.lastIndexOf("."));

            PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                .object(fileName)	//文件名
                .bucket(MinIoController.BUCKETNAME)  //存储目录名
                .stream(file.getInputStream(), file.getSize(), -1).build(); //文件流，以及大小，-1代表不分片

            //客户端执行上传
            minioClient.putObject(putObjectArgs);//核心代码putObject
            
            return R.ok("上传成功",fileName);//后端接口上传成功响应包装文件名作为数据进行返回给前端!
        } catch (Exception e) {
            return R.fail();
        }
    }

    //删除文件
    @DeleteMapping("/{name}")//注意文件名通过路径变量来传入
    public R<Void> delete(@PathVariable("name")String name) {
        try {
            // 构建一个Minio客户端
            MinioClient minioClient = MinioClient.builder()
                //创建容器时指定的账号
                .credentials(MinIoController.ACCESSKEY, MinIoController.SECREKEY)
                //上传地址
                .endpoint(MinIoController.ADDRESS).build();

            minioClient.removeObject(MinIoController.BUCKETNAME, name);//核心代码removeObject
            
            return R.ok();
        } catch (Exception e) {
            return R.fail();
        }
    }
}